package com.github.live.component;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.live.R;
import com.github.live.adapter.EpgBodyAdapter;
import com.github.live.adapter.EpgHeaderAdapter;
import com.github.live.base.BookingManager;
import com.github.live.manager.ChannelsManager;
import com.github.live.base.KeyEventDispatcher;
import com.github.live.base.VisibleComponent;
import com.github.live.manager.LiveInitializer;
import com.github.live.util.LiveDialog;
import com.github.livebase.bean.Channel;
import com.github.livebase.bean.EpgInformation;
import com.github.livebase.event.Event;
import com.github.livebase.event.EventBus;
import com.github.livebase.event.EventListener;
import com.github.livebase.event.SimpleEventBus;
import com.github.livebase.util.base.CollectionsUtil;
import com.github.livebase.util.base.DateUtil;
import com.owen.tvrecyclerview.widget.TvRecyclerView;
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ReplayEpgView
 * @description:
 * @author: biao532
 * @create: 2024-01-03 16:49
 * @Version 1.0
 **/
public class ReplayEpgView extends LinearLayout implements EventListener, ChannelsManager.ChangeEvent.DefaultChangeEvent, VisibleComponent {
    private KeyEventTvRecyclerView header;
    private KeyEventTvRecyclerView body;
    private EpgHeaderAdapter headerAdapter;
    private EpgBodyAdapter bodyAdapter;
    private Channel currentChannel;
    private EpgInformation replaying;
    private TextView title;
    private AlertDialog alertDialog;
    public ReplayEpgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ReplayEpgView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.component_replay_epg, this);
        title = findViewById(R.id.replay_title);
        header = findViewById(R.id.epg_date_bar);
        body = findViewById(R.id.epg_info_bar);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        header.setLayoutManager(layoutManager);

        headerAdapter = new EpgHeaderAdapter();
        header.setAdapter(headerAdapter);
        header.setSelected(false);
        header.setFocusable(false);
        header.setClickable(false);

        bodyAdapter = new EpgBodyAdapter();
        body.setAdapter(bodyAdapter);
        header.setOnItemListener(new TvRecyclerView.OnItemListener() {
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position) {

            }

            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position) {
                headerSelect(position);
            }

            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position) {

            }
        });

        body.setHasFixedSize(true);
        body.setLayoutManager(new V7LinearLayoutManager(getContext(), 1, false));
        body.setOnItemListener(new TvRecyclerView.OnItemListener() {
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position) {

            }

            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position) {
                bodyAdapter.setSelectedChannelIndex(position);
            }

            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position) {
                bodyClick(position);
            }
        });
        body.setEnabled(true);
        body.setFocusable(true);
        body.setKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatch(int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    return false;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    int index = headerAdapter.getSelectedChannelIndex() - 1;
                    if (index < 0) {
                        index = headerAdapter.getItemCount() - 1;
                    }
                    headerSelect(index);
                    return true;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    int index = headerAdapter.getSelectedChannelIndex() + 1;
                    if (index >= headerAdapter.getItemCount()) {
                        index = 0;
                    }
                    headerSelect(index);
                    return true;
                }
                return false;
            }
        });
        LiveInitializer.getInitializer()
                .getChannelsManager().addChangeEvent(this);
        initData();
    }

    public void setCurrentChannel(Channel currentChannel) {
        this.currentChannel = currentChannel;
        title.setText("回看&"+currentChannel.getName());
    }

    private void initData() {
        List<Date> dates = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, -3);
        for (int i = 0; i < 7; i++) {
            dates.add(c.getTime());
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        headerAdapter.setData(dates);
        bodyAdapter.setData(Arrays.asList(EpgInformation.NO_INFORMATION));
        header.setSelection(3);
        headerAdapter.setActiveChannelIndex(3);
    }

    @Override
    public void show() {
        this.setVisibility(VISIBLE);
        headerSelect(headerAdapter.getActiveChannelIndex());
    }

    @Override
    public void hide(long delay) {
        this.setVisibility(GONE);
    }

    @Override
    protected void onDetachedFromWindow() {
        SimpleEventBus.getDefault().unregister(EventBus.EVENT_CHANGE_DATE, this);
        LiveInitializer.getInitializer().getChannelsManager().removeChangeEvent(this);
        super.onDetachedFromWindow();
    }

    private void headerSelect(int position) {
        headerAdapter.setSelectedChannelIndex(position);
        Date date = headerAdapter.getItem(position);
        List<EpgInformation> epgs = LiveInitializer.getInitializer()
                .getEpgManager()
                .getEpgInfosByDay(currentChannel,
                Integer.valueOf(DateUtil.format(new SimpleDateFormat("yyyyMMdd"), date)));
        bodyAdapter.setData(epgs);
        // 非活跃 且 非今天
        if (position != 3 && position != headerAdapter.getActiveChannelIndex()) {
            body.setSelection(0);
            return;
        }
        ChannelsManager channelsManager = LiveInitializer.getInitializer().getChannelsManager();
        // 活跃标签为今天
        if (position == 3 && position == headerAdapter.getActiveChannelIndex()) {
            int index = -1;
            if (channelsManager.isLive()) {
                long now = System.currentTimeMillis();
                index = CollectionsUtil.firstIndex(epgs, (e) -> {
                    return DateUtil.betweenAnd(now, e.getStart(), e.getEnd());
                });
            }
            else {
                index = CollectionsUtil.firstIndex(epgs, (e) -> {
                    return  e.getStart() == replaying.getStart() &&  e.getEnd() == replaying.getEnd();
                });
            }
            if (index != -1) {
                body.setSelection(index);
                bodyAdapter.setActiveChannelIndex(index);
            }
            return;
        }
        // 是今天 / 活跃标签

        int index = -1;
        if (channelsManager.isLive() || position == 3) {
            long now = System.currentTimeMillis();
            index = CollectionsUtil.firstIndex(epgs, (e) -> {
                return DateUtil.betweenAnd(now, e.getStart(), e.getEnd());
            });
        }
        else {
            index = CollectionsUtil.firstIndex(epgs, (e) -> {
                return  e.getStart() == replaying.getStart() &&  e.getEnd() == replaying.getEnd();
            });
        }
        if (index != -1) {
            body.setSelection(index);
            bodyAdapter.setActiveChannelIndex(index);
        }
    }

    private void showDialog(String message) {
        if (alertDialog == null) {
            alertDialog = new LiveDialog(getContext());
            alertDialog.setTitle(R.string.tips_title);
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getString(R.string.confirm), (DialogInterface dialog, int which)-> {
                dialog.dismiss();
            });
            alertDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        alertDialog.setMessage(message);
        alertDialog.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).requestFocus();
    }
    private void showDialog(int resId) {
        String str = getContext().getResources().getString(resId);
        showDialog(str);
    }
    private void bodyClick(int position) {
        EpgInformation information = bodyAdapter.getItem(position);
        if (information == null || information == EpgInformation.NO_INFORMATION) {
            return;
        }

        ChannelsManager cm = LiveInitializer.getInitializer().getChannelsManager();
        long now = System.currentTimeMillis();
        if (DateUtil.betweenAnd(now, information.getStart(), information.getEnd())) {
            this.replaying = null;
            headerAdapter.setActiveChannelIndex(3);
            cm.replayOver();

            bodyAdapter.setActiveChannelIndex(position);
            // hide();
            // 直播中;
            return;
        }
        if (!cm.isLive()
                && position == bodyAdapter.getActiveChannelIndex()
                && now > information.getEnd()) {
            // hide();
            // 回看中;
            return;
        }

        if (now < information.getStart()) {
            BookingManager booking = BookingManager.singleton();
            if (booking.isBooking(information)) {
                if (booking.remove(information)) {
                    bodyAdapter.notifyItemChanged(position);
                    showDialog("已取消预约");
                    return;
                }
            }
            else {
                if (booking.booking(information)) {
                    bodyAdapter.notifyItemChanged(position);
                    showDialog("预约成功");
                    return;
                }
            }
            showDialog("发生错误，操作失败");
            hide();
            // 可预约;
            return;
        }

        if (cm.getCurrentSource().supportedReplay()){
            // 可回看;
            headerAdapter.setActiveChannelIndex(headerAdapter.getSelectedChannelIndex());
            bodyAdapter.setActiveChannelIndex(position);
            this.replaying = information;
            cm.replay(information);
        }
        else {
            return;
            // showDialog(R.string.unsupported_replay);
            // 不支持回看;
        }
        hide();
    }

    @Override
    public void onEvent(Event event) {
        if (!Event.isEvent(event, EventBus.EVENT_CHANGE_DATE)) {
            return;
        }
        initData();
    }

    @Override
    public void onLiveChange(Channel.Source source, EpgInformation information, boolean isLive) {
        if (isLive) {
            header.setSelection(3);
        }
    }
}
